package com.focus.wecenter.web.controller;

import com.focus.wecenter.pojo.AnswerComment;
import com.focus.wecenter.pojo.Question;
import com.focus.wecenter.service.AnswerService;
import com.focus.wecenter.service.QuestionService;
import com.focus.wecenter.util.FunUtil;
import com.focus.wecenter.util.Message;
import com.focus.wecenter.web.controller.common.BaseController;
import com.focus.wecenter.web.vo.QuestionPublishForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * 问题控制器
 *
 * @author Lv Jing
 * @date 2018年01月05日 21:15
 */
@Controller
@RequestMapping("/question")
public class QuestionController extends BaseController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private AnswerService answerService;

    /**
     * 显示问题发布页面
     */
    @RequestMapping("/publish")
    public String showPublish() {
        return "/question/publish";
    }

    /**
     * 问题发布处理
     * @param questionPublishForm 问题表单
     * @return 消息
     */
    @RequestMapping(value = "/ajax/publish", method = RequestMethod.POST)
    @ResponseBody
    public Message publish(QuestionPublishForm questionPublishForm, HttpSession session) {
        Message message = new Message();
        // 标题检查
        if (FunUtil.isEmpty(questionPublishForm.getTitle())) {
            message.setSuccess(false);
            message.setData("请输入问题标题");
            return message;
        }
        // 分类检查
        if ("0".equals(questionPublishForm.getCategory())) {
            message.setSuccess(false);
            message.setData("请选择问题分类");
            return message;
        }
        // 标题字数限制
        if (questionPublishForm.getTitle().length() <= 5) {
            message.setSuccess(false);
            message.setData("问题标题字数不得少于 5 个字");
            return message;
        }
        // 话题检查
        if (FunUtil.isEmpty(questionPublishForm.getTopics())) {
            message.setSuccess(false);
            message.setData("请为问题添加话题");
            return message;
        }

        /*检查成功，添加问题*/
        // 设置该问题的用户
        try {
            questionPublishForm.setAsk_user_id(this.getSessionUserID(session)+"");
            Question question = questionService.publishQuestion(questionPublishForm);
            message.setSuccess(true);
            message.setData("/question/" + question.getId());
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setData("服务器未知异常");
        }
        return message;
    }

    /**
     * 显示问题详情
     * @param questionID 问题ID
     */
    @RequestMapping("/{questionID}")
    public String showDetail(@PathVariable int questionID, Model model, HttpSession session) {
        Question result = questionService.findQuestionByID(questionID);
        model.addAttribute("question", result);
        boolean isFocus = questionService.isFocus(questionID, this.getSessionUserID(session));
        model.addAttribute("focus", isFocus);
        return "/question/detail";
    }

    /**
     * 关注或取关问题
     * @param questionID 问题ID
     */
    @RequestMapping(value = "/ajax/focus", method = RequestMethod.POST)
    @ResponseBody
    public Message focusQuestion(@RequestParam("question_id") int questionID, HttpSession session) {
        try {
            return questionService.focus(questionID, this.getSessionUserID(session));
        } catch (Exception e) {
            e.printStackTrace();
            Message message = new Message();
            message.setSuccess(false);
            message.setData("服务器未知异常");
            return message;
        }
    }

    /**
     * 保存回答
     * @param questionID 问题ID
     * @param content 回答内容
     */
    @RequestMapping(value = "/ajax/save_answer", method = RequestMethod.POST)
    @ResponseBody
    public Message saveAnswer(@RequestParam("question_id") int questionID, String content, HttpSession session) {
        Message message = new Message();
        if (FunUtil.isEmpty(content)) {
            message.setSuccess(false);
            message.setData("请输入回复内容");
            return message;
        }
        if (content.length() < 10) {
            message.setSuccess(false);
            message.setData("回复内容字数不得少于 10 字节");
            return message;
        }
        try {
            answerService.saveAnswer(questionID, content, this.getSessionUserID(session));
            message.setSuccess(true);
            message.setData("提交成功");
            message.put("url", "question/" + questionID);
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setData("回答提交失败");
        }
        return message;
    }

    /**
     * 对回答进行投票
     * @param answerID 问题ID
     */
    @RequestMapping(value = "/ajax/answer_vote", method = RequestMethod.POST)
    @ResponseBody
    public Message agreeAnswer(@RequestParam("answer_id") int answerID, int type) {
        Message message = new Message();
        try {
            answerService.voteAnswer(answerID, type);
            message.setSuccess(true);
        } catch (Exception e) {
            message.setSuccess(false);
            message.setData("参数错误，不能进行投票");
        }
        return message;
    }

    /**
     * 获取评论列表 TODO:评论时间显示优化
     * @param answerID 回答ID
     */
    @RequestMapping(value = "/ajax/get_answer_comments/answer_id-{answerID}", method = RequestMethod.GET)
    public String getAnswerComments(@PathVariable int answerID, Model model) {
        Set<AnswerComment> result = answerService.findAnswerCommentsByID(answerID);
        model.addAttribute("result", result);
        // 拼装评论html FIXME:commentHtml警告
        // StringBuilder commentHtml = new StringBuilder();
         return "question/answer_comment_template";
    }

    /**
     * 保存回答的评论
     * @param answerID 回答ID      ajax/save_answer_comment/answer_id
     */
    @RequestMapping(value = "/ajax/save_answer_comment/answer_id-{answerID}", method = RequestMethod.POST)
    @ResponseBody
    public Message saveAnswerComment(@PathVariable int answerID, String message, HttpSession session) {
        Message msg = new Message();
        if (FunUtil.isEmpty(message)) {
            msg.setSuccess(false);
            msg.setData("请输入评论内容");
            return msg;
        }
        try {
            // 保存评论
            answerService.saveAnswerComment(message, this.getSessionUserID(session), answerID);
            msg.setSuccess(true);
            msg.put("id", answerID);
            msg.put("type", "answer");
        } catch (Exception e) {
            e.printStackTrace();
            msg.setSuccess(false);
            msg.setData("参数错误，评论失败");
        }
        return msg;
    }

    @RequestMapping("/ajax/fetch_question_category")
    @ResponseBody
    public Message getCategory() {
        /*
        id	2
        title	WeCenter 程序
        description	null
        sort	0
        parent_id	0
        url_token	2
        */
        return new Message();
    }
}